package com.shengyin.ec.controller.account;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.shengyin.ec.controller.order.OrderBoughtGoodsParam;
import com.shengyin.ec.exception.ControllerException;
import com.shengyin.ec.model.entity.BookInfo;
import com.shengyin.ec.model.entity.Company;
import com.shengyin.ec.model.entity.CompanyOrder;
import com.shengyin.ec.model.entity.Favoriten;
import com.shengyin.ec.model.entity.Goods;
import com.shengyin.ec.model.entity.Orders;
import com.shengyin.ec.model.entity.Personal;
import com.shengyin.ec.model.entity.Province;
import com.shengyin.ec.model.entity.Receiver;
import com.shengyin.ec.service.account.BookInfoService;
import com.shengyin.ec.service.account.FavoritenService;
import com.shengyin.ec.service.account.PersonalService;
import com.shengyin.ec.service.account.ProvinceService;
import com.shengyin.ec.service.account.ReceiverService;
import com.shengyin.ec.service.alliance.AllianceService;
import com.shengyin.ec.service.companyorder.CompanyOrderService;
import com.shengyin.ec.service.goods.GoodsService;
import com.shengyin.ec.service.order.OrderService;
import com.shengyin.ec.service.payment.PaymentService;

@Controller
public class PersonalController {

	@Autowired
	PersonalService personalService;
	
	@Autowired
	ProvinceService provinceService;
	
	@Autowired
	ReceiverService receiverService;
	
	@Autowired
	OrderService orderService;
	
	@Autowired
	FavoritenService favoritenService;
	
	@Autowired
	GoodsService goodsService;
	
	@Autowired
	PaymentService PaymentService;
	
	@Autowired
	Md5PasswordEncoder passwordEncoder;

	@Autowired
	AllianceService allianceService;
	
	@Autowired 
	CompanyOrderService companyOrderService;
	
	@Autowired 
	BookInfoService bookInfoService;
	
	@RequestMapping("/toPersonalList.do")
	public String toPersonalList(Model model,HttpServletRequest request){
		
		int offset = 0;
		try {
			offset = Integer.valueOf(request.getParameter("pager.offset"));
			System.out.println("offset:" + offset);
		} catch (Exception ex) {
			System.out.println("初始化页数.......");
		}
		List<Personal> personalList =personalService.getPersonalList(offset,20);
		Long maxsize = personalService.getTotal();
		model.addAttribute("personalList", personalList);
		model.addAttribute("maxSize",maxsize);
		return "/admin/users/personalList";
		}
	
	@RequestMapping("/searchUserByName.do")
	public String searchUserByName(Model model,HttpServletRequest request){
		
		String keyword = request.getParameter("keyword");
		keyword = '%'+keyword+'%';
		List<Personal> personalList = personalService.getPersonalByUsername(keyword,0,20);
		long maxSize = personalService.getPersonalByUsername(keyword).size();
		model.addAttribute("personalList", personalList);
		model.addAttribute("maxSize",maxSize);
		return "/admin/users/personalList";
	}
	
	
	@RequestMapping("/toViewPersonal.do")
	public String toPersonalModify(@RequestParam("id") long id,Model model){
		Personal personal=personalService.getPersonalById(id);
		model.addAttribute("personal", personal);
		return "/admin/users/personalView";
		}
	
	@RequestMapping("/regisPersonal.do")
	public String createPersonal(PersonalForm personalForm,Model model,HttpServletRequest request){
		Personal personal =new Personal();
		try {
			personalForm.setPassword(passwordEncoder.encodePassword("shengyin", personalForm.getPassword()));
			BeanUtils.copyProperties(personal, personalForm);
			
			personalService.createPersonal(personal);
			personal=personalService.getPersonalById(personal.getId());
			
			WebUtils.setSessionAttribute(request, "user", personal);
			
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
    	//model.addAttribute("regMsg", "success");
		String result = "redirect:";
		if(personalForm.getDirectUrl()!=null&&personalForm.getDirectUrl().startsWith("http://localhost")){
			result += personalForm.getDirectUrl();
		}else{
			result += "http://localhost:8080/ec/";
		}
		return result;		
		
	}
	
	@RequestMapping("/personalDelete.do")
	public String deletePersonal(@RequestParam("id") long id)
	{
		personalService.removePersonalById(id);
		return "redirect:/toPersonalList.do";
	}
	
	@RequestMapping("/allPersonalDelete.do")
	public String deleteAllPersonal(HttpServletRequest request )
	{
		String [] ids=request.getParameterValues("id");
		personalService.deleteAllPersonal(ids);
		return "redirect:/toPersonalList.do";
	}
	
	
		
		//modified by lcl 2012-09-09
		@RequestMapping("/toAccount.do")
		public String toAccount(Model model, HttpServletRequest request){
			HttpSession session = request.getSession();
			Personal  personal = (Personal)session.getAttribute("user");
			Company   allianceCompany = (Company)session.getAttribute("alliance");
			
			if(personal != null){		
				return "redirect:/view/user/memberAccount.jsp";
			}
			else if(allianceCompany != null){
				return "redirect:/view/alliance/allianceAccount.jsp";
			}
			else{
				return "redirect:/view/user/login.jsp";
			}
		}
		
	    @ExceptionHandler({ControllerException.class})  
		   public String exception(ControllerException e,HttpServletRequest request) {  
		       request.setAttribute("error", e.getMessage());
		        return "/admin/error/error";  
		    } 
	    
	  
	  	@RequestMapping("/toUserInfo.do")
	  	public String toUserInfo(Model model, HttpServletRequest request){
	  		HttpSession session = request.getSession();
	  		Personal personal = (Personal)session.getAttribute("user");
	  		List<Province> province = provinceService.getProvinceList();
	  		
	  		model.addAttribute("user", personal);
	  		model.addAttribute("province", province);
	  		
	  		return "/view/user/memberInfo";
	  	}
	  	
	  	
	  	
	  //add by lcl 2012-3-20
	  	@RequestMapping(value ="/checkUserNameExist.do", method = RequestMethod.GET)
		@ResponseBody
		public ModelMap checkUserNameExist(Model model, @RequestParam("username") String username) {
	  		boolean isExist;
			 ModelMap modelMap = new ModelMap();
			List<Personal> list = personalService.getPersonalByUsername(username.trim());
			if(list.size() == 0)
				isExist = false;
			else
				isExist = true;
			modelMap.addAttribute("isExist", isExist);
			return modelMap;
		}
	    
	  	 //add by lcl 2012-3-21
	  	@RequestMapping("/checkUserPsw.do")
	  	public String checkUserPsw(Model model, PersonalForm personalForm, @RequestParam("id") long id){
	  		Personal personal = personalService.getPersonalById(id);
	  		personalForm.setPassword(passwordEncoder.encodePassword("shengyin", personalForm.getPassword()));
	  		personal.setPassword(personalForm.getPassword());
	  		personalService.updatePersonal(personal);
	  		model.addAttribute("modifyUserPswRet", true);
	  		
	  		return "/showInfo";
	  	}
	  	
	  	
	  	//add by lcl 2012-3-23
		 @RequestMapping("/modifyPersonalInfo.do")
		 public String modifyPersonalInfo(Model model, PersonalForm personalForm,@RequestParam("id") long id){
			 	Personal personal = new Personal();
			 	
		  		try{
		  			BeanUtils.copyProperties(personal, personalForm);
		  			personal.setId(id);
		  			personal.setPassword(personalService.getPersonalById(id).getPassword());
		  			personalService.updatePersonal(personal);
		  	
		  		}catch (InvocationTargetException e) {
						e.printStackTrace();
		  		}catch (IllegalAccessException e) {
		  				e.printStackTrace();
		  		}
		  		model.addAttribute("modifyUserRet", true);
		  		 Personal personal1 = personalService.getPersonalById(id);
		  		model.addAttribute("user", personal1);
		  		
		  		return "/view/user/userInfo";
		  	}
		 
	  	
	    
	  	
	  	//add by lcl 2012-07-30
	  	@RequestMapping(value = "/checkOldPsw.do", method = RequestMethod.GET)
		@ResponseBody
		public ModelMap checkOldPsw(
				@RequestParam("oldpsw") int oldpsw, HttpServletRequest request) {
			ModelMap modelMap = new ModelMap();
			HttpSession session = request.getSession();
			Personal personal = (Personal)session.getAttribute("user");
			String oldpassword =  passwordEncoder.encodePassword("shengyin", oldpsw);
			boolean pswEquals = false;
			
			if((personal.getPassword()).equals(oldpassword))
				pswEquals = true;

			modelMap.addAttribute("pswEquals", pswEquals);
			
			return modelMap;
		}
	  	
		 @RequestMapping("/toUserPasswd.do")
		 public String toUserPasswd(){
		  		
		  		return "/view/user/memberChangePsw";
		  	}
		 
		 @RequestMapping("/changePsw.do")
		 public String changePsw(Model model, @RequestParam("id") long id){
		  		
		  		return "/view/user/updatePsw";
		  	}
		 
		 @RequestMapping("/toUserReceiver.do")
		 public String toUserReceiver(Model model, HttpServletRequest request){
			 HttpSession session = request.getSession();
			 Personal personal = (Personal)session.getAttribute("user");			 
			 List<Receiver> receiverList = receiverService.getReceiverListById(personal.getId());
			 List<Province> provinceList = provinceService.getProvinceList();
			 boolean noReceiver = false; 
			 
			 if(receiverList.size() == 0)
				 noReceiver = true;
			 
			 model.addAttribute("receiverList", receiverList);
			 model.addAttribute("province", provinceList);
			 model.addAttribute("noReceiver", noReceiver);
			
		  	 return "/view/user/userReceiver";
		  	}
		 
		 @RequestMapping("/noReceiverRecord.do")
		 public String noReiverRecord(Model model){
			 	boolean noRecord = true;
			 	List<Province> provinceList = provinceService.getProvinceList();
			 	
			 	model.addAttribute("noRecord", noRecord);
			 	model.addAttribute("province", provinceList);
			 	
		  		return "/view/user/userReceiver";
		  	}
		 
		 //add by lcl 2012-09-08
		    @RequestMapping("/toFavoriten.do")
		    public String toFavoriten(Model model,HttpServletRequest request){
		    	HttpSession session = request.getSession();
				Personal  personal = (Personal)session.getAttribute("user");
				List<Favoriten> favoritenList = favoritenService.getFavoritenByUserId(personal.getId());
				List<OrderBoughtGoodsParam> obgpList = new ArrayList();
				
				for(int i = 0; i < favoritenList.size(); i++){
					Goods goods = goodsService.getGoodsByProductId(favoritenList.get(i).getProductId());
					OrderBoughtGoodsParam obgp = new OrderBoughtGoodsParam();
					obgp.setProductName(goods.getProductName());
					obgp.setProductPicture(goods.getProductPicture());
					obgp.setOurPrice(goods.getOurPrice());
					obgp.setCreateDate(favoritenList.get(i).getCreateDate());
					obgpList.add(obgp);
				}
				
				model.addAttribute("favoritenList", obgpList);
				return "/view/user/memberFavoriten"; 
		    }
		    
		  //add by lcl 2012-09-14
		    @RequestMapping("/toMemberAddBookingInfo.do")
			 public String toMemberAddBookingInfo(Model model){
				 	
			  		return "/view/user/memberAddBookingInfo";
			  	}
		    
		  //add by lcl 2012-09-14
		    @RequestMapping("/toMemberBookingInfoList.do")
			 public String toMemberBookingInfoList(Model model,HttpServletRequest request){
		    	HttpSession session = request.getSession();
		    	Personal personal = (Personal)session.getAttribute("user");
		    	List<BookInfo>  bookInfoList = bookInfoService.getBookInfoListById(personal.getId());
		    	
		    	model.addAttribute("bookInfoList", bookInfoList);
		    	
			  	return "/view/user/memberBookingInfoList";
			  	}
		    
		    
		    @RequestMapping("/personalExit.do")
		    public String personalExit(HttpServletRequest request){
		    	WebUtils.setSessionAttribute(request, "user", null);
		    	return "redirect:/toIndex.do";
		    }
		    
		    //add by lcl 2012-10-10
		    @RequestMapping("/memberAddBookInfo.do")
			 public String memberAddBookInfo(HttpServletRequest request, BookInfoForm bookInfoForm, Model model) {
		    	BookInfo bookInfo = new BookInfo();
		 		HttpSession session = request.getSession();
				Personal user = (Personal)session.getAttribute("user");
				
				try {
					BeanUtils.copyProperties(bookInfo, bookInfoForm);
					String bookTime = bookInfoForm.getYYYY() + bookInfoForm.getMM() + bookInfoForm.getDD();
					bookInfo.setBookTime(bookTime);
					bookInfo.setUserId(user.getId());
			  
					bookInfoService.createBookInfo(bookInfo);
			  		return "/view/user/memberAddBookingInfo";
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
				return "/view/user/memberAddBookingInfo";
			  	}
		    
		  //add by lcl 2012-10-10
		    @RequestMapping("/memberUpdate.do")
			 public String memberUpdate(HttpServletRequest request, PersonalForm personalForm, Model model) {
		 		HttpSession session = request.getSession();
				Personal user = (Personal)session.getAttribute("user");
				String password = user.getPassword();
				try {
					BeanUtils.copyProperties(user, personalForm);
					user.setPassword(password);	  
					personalService.updatePersonal(user);
					
			  		return "/view/user/memberInfo";
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			
				return "/view/user/memberInfo";
			  	}
		    
		    @RequestMapping("/memberUpdatePsw.do")
			 public String allianceUpdatePsw(PersonalForm personalForm, Model model, HttpServletRequest request) {
		  		HttpSession session = request.getSession();
		  		Personal user = (Personal)session.getAttribute("user");
		  		user.setPassword(passwordEncoder.encodePassword("shengyin", personalForm.getPassword()));
		  	    personalService.updatePersonal(user);
		  		
				return "/view/user/memberChangePsw";
		 	  	}
		    
		  //add by lcl 2012-09-14
		    @RequestMapping("/toMemberUpdatePsw.do")
			 public String toMemberUpdatePsw(Model model){
				 	
			  	return "/view/user/memberChangePsw";
			  	}
		    
		    //I donn't know why keyword value haven't been pass here
		    /*  @RequestMapping("/searchBookInfoByKeywords.do")
			 public String searchBookInfoByKeywords(KeyWords keyWords, Model model, HttpServletRequest request) {
		  		String keyword = keyWords.getKeyword();
		  		System.out.println("-------------------------------------"+keyword);
		  		System.out.println("-------------------------------------"+keyword);
		  		System.out.println("-------------------------------------"+keyword);
		  		List<BookInfo> bookInfoList =bookInfoService.getBookInfoListByKeywords(keyword);		  		
		  		model.addAttribute("bookInfoList", bookInfoList);
		  		
				return "/view/user/memberBookingInfoList";
		 	  	}
		    */
		   /* @RequestMapping("/getBookInfoListByBookItem.do")
			 public String getBookInfoListByBookItem(Model model, HttpServletRequest request) {
		    	HttpSession session = request.getSession();
		  		Personal user = (Personal)session.getAttribute("user");
		  		List<BookInfo> bookInfoList =bookInfoService.getBookInfoListByBookItem(user.getId());		  		
		  		model.addAttribute("bookInfoList", bookInfoList);
		  		
				return "/view/user/memberBookingInfoList";
		 	  	}
		    
		    @RequestMapping("/getBookInfoListByStatus.do")
			 public String getBookInfoListByStatus( Model model, HttpServletRequest request) {
		    	HttpSession session = request.getSession();
		  		Personal user = (Personal)session.getAttribute("user");
		  		List<BookInfo> bookInfoList =bookInfoService.getBookInfoListByStatus(user.getId());		  		
		  		model.addAttribute("bookInfoList", bookInfoList);
		  		
				return "/view/user/memberBookingInfoList";
		 	  	}*/
		    
		    
}

